from django.shortcuts import render, redirect
from web.models import Account_Admin
from web.elm import PageDocument
from django import forms


class Account_Admin_Form(forms.ModelForm):
    class Meta:
        model = Account_Admin
        # fields = ['user_name', 'user_account', 'user_password', 'user_email', 'user_phone', 'platform_name',
        #           'platform_type', 'platform_url', 'platform_icon']
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {'class': 'layui-input', 'autocomplete': 'off'}


# 账号管理
# 添加账号
def account_admin_add(request):
    if request.method == 'GET':
        form = Account_Admin_Form()
        return render(request, '账号管理/添加账号.html', context = {'form': form})
    if request.method == 'POST':
        form = Account_Admin_Form(data = request.POST)
        if form.is_valid():
            form.save()
            return redirect('/web/account_admin/index/')
        else:
            return render(request, '账号管理/添加账号.html', context = {'form': form})


# 首页
def account_admin_index(request):
    global account_admin_list
    Select_Type = int(request.GET.get('Select_Type', 0))
    select_params = request.GET.get('select_params', '')
    if Select_Type == 0:
        account_admin_list = Account_Admin.objects.all()
    elif Select_Type == 1:
        account_admin_list = Account_Admin.objects.filter(user_account__contains = select_params)
    elif Select_Type == 2:
        account_admin_list = Account_Admin.objects.filter(user_name__contains = select_params)
    elif Select_Type == 3:
        account_admin_list = Account_Admin.objects.filter(platform_name__contains = select_params)
    else:
        account_admin_list = Account_Admin.objects.all()
    result = {
        "account_admin_list": account_admin_list
    }
    return render(request, '账号管理/首页.html', context = result)


# 编辑账号
def account_admin_edit(request, nid):
    user_data = Account_Admin.objects.filter(id = nid).first()
    form = Account_Admin_Form(instance = user_data)
    if request.method == 'GET':
        result = {
            "user_data": user_data,
            "form": form
        }
        return render(request, '账号管理/编辑账号.html', context = result)
    else:
        form = Account_Admin_Form(data = request.POST, instance = user_data)
        if form.is_valid():
            form.save()
            return redirect('/web/account_admin/index/')
        else:
            result = {
                "user_data": user_data,
                "form": form
            }
            return render(request, '账号管理/编辑账号.html', context = result)

# 上传网站图标
def account_admin_upload(request):
    if request.method == 'GET':
        return render(request, '账号管理/上传图标.html')


# 账号管理
